/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/* eslint-disable react/jsx-no-bind */
/**
 * 上一站、下一站设置
 *  */
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form, Input, Button, message, Row, Col, Popconfirm, Table } from 'antd';
import { getLStorage } from '@/utils/utils';
import styles from '../style.less';

const FormItem = Form.Item;

@connect(({ allocation, loading, user }) => ({
  allocation,
  userInfo: user.currentUser.user_info,
  getSetList: loading.effects['allocation/getSetList'],
  deletSetList: loading.effects['allocation/deletSetList'],
  addSetList: loading.effects['allocation/addSetList'],
}))
@Form.create({ name: 'config' })
class StationSeting extends PureComponent {
  constructor(props) {
    super(props);
    const { phone, gp_area_ids = [], area_ids } = this.props.userInfo || {};
    const isCompany = area_ids == '*';
    const cacheAreaId = getLStorage(`KB_GP_AREA_${phone}`);
    const area_id = gp_area_ids.includes(cacheAreaId)
      ? cacheAreaId
      : isCompany
        ? '0'
        : gp_area_ids[0];
    this.state = {
      area_id,
    };
    this.columns = [
      {
        title: '编号',
        dataIndex: 'station_code',
        key: 'station_code',
        align: 'center',
      },
      {
        title: '名称',
        dataIndex: 'station_name',
        key: 'station_name',
        align: 'center',
      },
      {
        title: '操作',
        align: 'center',
        render: (text, record) => (
          <Popconfirm
            placement="top"
            title={`是否删除该${this.props.type == 'prevStation' ? '上' : '下'}一站`}
            onConfirm={this.delete.bind(this, record)}
            okText="确定"
            cancelText="取消"
          >
            <a>删除</a>
          </Popconfirm>
        ),
      },
    ];
  }

  componentDidMount() {
    this.getList();
  }

  componentDidUpdate(prevPros) {
    if (prevPros.activeKey !== this.props.activeKey && this.props.activeKey == this.props.type) {
      this.getList();
    }
  }

  getList() {
    const {
      dispatch,
      setRecord: { type, branch_code },
      form: { resetFields },
    } = this.props;
    const { area_id } = this.state;
    const station_type = this.props.type == 'prevStation' ? '2' : '1'; // 1：下一站，2：上一站
    if (this.props.type == 'prevStation' && type !== 'sto') {
      // 上一站使用setRecord传递过来的数据，除申通外，申通需要调用接口（nextList）
      dispatch({
        type: 'allocation/getCompanyInfoByBranchCode',
        payload: {
          brand: type,
          branch_code,
          area_id,
        },
      });
      resetFields();
    } else {
      dispatch({
        type: 'allocation/getSetList',
        payload: {
          brand: type,
          branch_code,
          station_type,
          area_id,
        },
      });
      resetFields();
    }
  }

  addConfig() {
    const {
      form,
      dispatch,
      setRecord: { id, type, branch_code },
      allocation: {
        prevList, // 上一站数据列表
      },
    } = this.props;
    const { area_id } = this.state;
    const isPrevOrNext = this.props.type == 'prevStation';

    if (isPrevOrNext && prevList.length >= 1) {
      message.error('不允许添加多个上一站！');
      return;
    }

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      if (isPrevOrNext && type !== 'sto') {
        // 上一站添加时，除申通外，都需调用原有接口（scanConfig），申通调用新接口（nextList）
        dispatch({
          type: 'allocation/setScanOption',
          payload: {
            id,
            brand: type,
            branch_code,
            previous_station_code: fieldsValue.station_code,
            previous_station_name: fieldsValue.station_name,
            area_id,
          },
        }).then(() => {
          this.getList();
        });
      } else {
        dispatch({
          type: 'allocation/addSetList',
          payload: {
            ...fieldsValue,
            brand: type,
            branch_code,
            station_type: isPrevOrNext ? '2' : '1',
            area_id,
          },
        }).then(() => {
          this.getList();
        });
      }
    });
  }

  delete(record) {
    const {
      setRecord: { type, branch_code },
      dispatch,
    } = this.props;
    const { area_id } = this.state;
    const { id, station_code } = record;
    if (this.props.type == 'prevStation' && type !== 'sto') {
      dispatch({
        type: 'allocation/setScanOption',
        payload: {
          id,
          brand: type,
          branch_code,
          previous_station_code: '',
          previous_station_name: '',
          area_id,
        },
      }).then(() => {
        this.getList();
      });
    } else {
      dispatch({
        type: 'allocation/deletSetList',
        payload: {
          brand: type,
          branch_code,
          id,
          station_code,
          area_id,
        },
      }).then(() => {
        this.getList();
      });
    }
  }

  render() {
    const {
      showDetail,
      form: { getFieldDecorator },
      allocation: {
        prevList, // 上一站数据列表
        nextList, // 下一站
      },
      getSetList,
      addSetList,
      setRecord: { brand, branch_code },
      type,
    } = this.props;

    const isPrevOrNext = type === 'prevStation'; // 判断是否是上一站还是下一站
    const title = isPrevOrNext ? '上一站' : '下一站';
    const tableData = isPrevOrNext ? prevList : nextList;

    return (
      <div className={styles.PostOption}>
        <Row type="flex" justify="space-between" align="middle" style={{ marginBottom: 24 }}>
          <Col span={18} className={styles.title}>
            <Form layout="inline">
              <FormItem>
                {getFieldDecorator('station_code', {
                  initialValue: '',
                  rules: [
                    {
                      required: true,
                      message: `请输入${title}编号`,
                    },
                    {
                      max: 15,
                      message: '请输入15位以内的字符！',
                    },
                    {
                      pattern: /^\w+$/,
                      message: '请输入字母或数字！',
                    },
                  ],
                })(<Input allowClear placeholder={`${title}编号`} />)}
              </FormItem>
              <FormItem>
                {getFieldDecorator('station_name', {
                  initialValue: '',
                  rules: [
                    {
                      max: 30,
                      message: '请输入30位以内的字符！',
                    },
                    {
                      required: true,
                      message: `请输入${title}名称`,
                    },
                  ],
                })(<Input allowClear placeholder={`${title}名称`} />)}
              </FormItem>
              <FormItem>
                <Button loading={addSetList} type="primary" onClick={this.addConfig.bind(this)}>
                  添加
                  {title}
                </Button>
              </FormItem>
            </Form>
          </Col>
          <Col span={6}>
            <Row type="flex" align="middle" justify="end">
              <Col>
                <span>{brand}</span>
                <span>（{branch_code}）</span>
              </Col>
              <Col>
                <Button type="primary" onClick={() => showDetail(false)}>
                  返回
                </Button>
              </Col>
            </Row>
          </Col>
        </Row>
        <Table
          className={styles.Tables}
          dataSource={tableData}
          columns={this.columns}
          rowKey="id"
          pagination={{ hideOnSinglePage: true }}
          loading={getSetList}
        />
      </div>
    );
  }
}

export default StationSeting;
